import 'package:campus_order/pages/app/merchant/home/view.dart';
import 'package:campus_order/pages/app/mine/view.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easylogger/flutter_logger.dart';
import 'package:get/get.dart';

import '../../utils/user_info_utils.dart';
import 'home/view.dart';
import 'order_food/view.dart';
import 'order_list/view.dart';

class AppLogic extends GetxController {
  final currentIndex = 0.obs;
  final userType = ''.obs;

  // 定义学生页面
  List<Widget> get studentPages => [
    HomePage(),
    OrderFoodPage(),
    OrderListPage(),
    MinePage(),
  ];

  // 定义商家页面
  List<Widget> get merchantPages => [
    MerchantHomePage(),
    OrderListPage(),
    MinePage(),
  ];

  // 当前显示的页面
  final pages = <Widget>[].obs;

  @override
  void onInit() {
    super.onInit();
    // 清除之前的页面设置
    pages.clear();
    currentIndex.value = 0;

    // 重新获取用户类型并设置页面
    getUserType();
    setupPages();

    // 打印日志以便调试
    Logger.d('初始化AppLogic，用户类型: ${userType.value}');
  }

  // 获取用户类型
  void getUserType() {
    try {
      // 直接从存储中获取最新的用户类型，而不是使用缓存的实例
      var loginModel = DataUtils().getLoginModel();
      userType.value = loginModel.userType ?? 'STUDENT';
      Logger.d('获取到用户类型: ${userType.value}');
    } catch (e) {
      userType.value = 'STUDENT';
      Logger.e('获取用户类型异常: $e');
    }
  }

  // 设置页面
  void setupPages() {
    if (userType.value == 'MERCHANT') {
      pages.assignAll(merchantPages);
    } else {
      pages.assignAll(studentPages);
    }
  }

  void changePage(int index) {
    currentIndex.value = index;
  }

  // 获取底部导航项
  List<BottomNavigationBarItem> getNavigationItems() {
    if (userType.value == 'MERCHANT') {
      return [
        BottomNavigationBarItem(
          icon: Icon(Icons.home),
          label: '首页',
        ),
        BottomNavigationBarItem(
          icon: Icon(Icons.receipt),
          label: '订单',
        ),
        BottomNavigationBarItem(
          icon: Icon(Icons.person),
          label: '我的',
        ),
      ];
    } else {
      return [
        BottomNavigationBarItem(
          icon: Icon(Icons.home),
          label: '首页',
        ),
        BottomNavigationBarItem(
          icon: Icon(Icons.restaurant_menu),
          label: '点餐',
        ),
        BottomNavigationBarItem(
          icon: Icon(Icons.receipt),
          label: '订单',
        ),
        BottomNavigationBarItem(
          icon: Icon(Icons.person),
          label: '我的',
        ),
      ];
    }
  }
}